package day02;

import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.Vector;

/**
 * 卖票练习
 */
@Slf4j
public class ExerciseSell {

    public static void main(String[] args) {
        TicketWindows ticketWindows = new TicketWindows(20000);
        List<Thread> list = new ArrayList<>();
        // 用来存储卖出去多少张票
        List<Integer> sellCount = new Vector<>();
//        ArrayList<Integer> sellCount = new ArrayList<>();
        for (int i = 0; i < 2000; i++) {
            Thread t = new Thread() {
                @Override
                public void run() {
                    int sell = ticketWindows.sell(randomAmount());
                    sellCount.add(sell);
                }
            };
            list.add(t);
            t.start();
        }
        // 等待每一条线程的执行
        list.forEach(t -> {
            try {
                t.join();
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        });
        log.debug("卖出去多少张: {}",sellCount.stream().mapToInt(c -> c).sum());
        // 剩余票数
        log.debug("剩余多少张：{}",ticketWindows.getCount());
    }

    // Random 为线程安全
    static Random random = new Random();
    // 随机数
    public static int randomAmount() {
        return random.nextInt(5) + 1;
    }

}


class TicketWindows{
    private int count;

    public TicketWindows (int count){
        this.count = count;
    }



    public synchronized int sell(int amount){
        if(this.count >= amount){
            this.count -= amount;
            return amount;
        }else{
            return 0;
        }
    }


    public int getCount(){
        return count;
    }

}
